package com.yunhe.authority.task;

import com.yunhe.authority.domain.company.Company;
import com.yunhe.authority.service.company.CompanyService;
import com.yunhe.common.exception.ArgumentErrorException;
import com.yunhe.common.exception.ModelNotFoundException;
import com.yunhe.common.exception.ObjectNotFoundException;
import com.yunhe.common.exception.UniqueConstraintsException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @ClassName: CompanyScheduled
 * @Description:
 * @author: GongDaCheng
 * @Date: 9:39 2021/8/18
 */

@Api(value = "CompanyScheduled",description = "定时任务",tags = "{CompanyScheduled}")
@RestController
@RequestMapping(value = "/companyScheduled")
@Slf4j
@EnableScheduling
@EnableAsync
public class CompanyScheduled {

    @Autowired
    private CompanyService companyService;

    @ApiOperation("租赁期限定时任务")
    @RequestMapping(value = "/leaseScheduled", method = RequestMethod.POST)
    @Scheduled(cron = "0 0 0 1/1 * ? ")
    @Async
    public void leaseScheduled() throws UniqueConstraintsException, ObjectNotFoundException, ModelNotFoundException, ArgumentErrorException, ParseException {
        log.info("租赁期限定时任务开始");
        long startTime = System.currentTimeMillis();
        List<Company> all = companyService.findAll();
        for (Company company : all) {
            String leaseEndStr = company.getLeaseEndTime();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            Date lease = sdf.parse(leaseEndStr);
            long leaseTime = lease.getTime();
            if (leaseTime < System.currentTimeMillis()){
                //如果租赁期限结束日期小于当前时间，企业离场
                companyService.companyLeave(company.getId());
            }
        }
        long endTime = System.currentTimeMillis();
        log.info("租赁期限定时处理数据所需要时间{}",(endTime-startTime));
        log.info("租赁期限定时任务结束");
    }
}
